/**
 * // Definition for a Node.
 * function Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */

function Node(val, next, random) {
  this.val = val;
  this.next = next;
  this.random = random;
};

let nodeMap = new Map();

/**
 * @param {Node} head
 * @return {Node}
 */
var copyRandomList = function (head) {

  if (head == null) {
    return null;
  }

  let nowNode;
  let nextNode;
  let randomNode;


  if ((nowNode = nodeMap.get(head)) == null) {
    nowNode = new Node(head.val, null, null);
  }

  nodeMap.set(head, nowNode);

  if ((randomNode = nodeMap.get(head.random)) == null) {
    randomNode = copyRandomList(head.random);
  }

  if ((nextNode = nodeMap.get(head.next)) == null) {
    nextNode = copyRandomList(head.next);
  }

  nowNode.next = nextNode;
  nowNode.random = randomNode;

  return nowNode;
};
